package com.ruyuan.rapid.core;

import com.ruyuan.rapid.common.constants.RapidBufferHelper;
import com.ruyuan.rapid.core.netty.NettyHttpClient;
import com.ruyuan.rapid.core.netty.NettyHttpServer;
import com.ruyuan.rapid.core.processor.NettyBatchEventProcessor;
import com.ruyuan.rapid.core.processor.NettyCoreProcessor;
import com.ruyuan.rapid.core.processor.NettyMpmcProcessor;
import com.ruyuan.rapid.core.processor.NettyProcessor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RapidContainer implements LifeCycle {

    private final RapidConfig rapidConfig;

    /**
     * netty接受http请求的核心类
     */
    private NettyHttpServer nettyHttpServer;

    /**
     * 处理请求的核心类
     */
    private NettyProcessor nettyProcessor;

    private NettyHttpClient nettyHttpClient;

    public RapidContainer(RapidConfig rapidConfig) {
        this.rapidConfig = rapidConfig;
        init();
    }

    @Override
    public void init() {
        //1构建核心处理器 processor
        NettyCoreProcessor nettyProcessor = new NettyCoreProcessor();
        // 2.是否开启缓冲
        String bufferType = rapidConfig.getBufferType();
        if (RapidBufferHelper.isFlusher(bufferType)) {
            this.nettyProcessor = new NettyBatchEventProcessor(this.rapidConfig, nettyProcessor);
        } else if (RapidBufferHelper.isMpmc(bufferType)) {
            this.nettyProcessor = new NettyMpmcProcessor(this.rapidConfig, nettyProcessor);
        } else {
            this.nettyProcessor = nettyProcessor;
        }
        // 3.创建 httpServer
        nettyHttpServer = new NettyHttpServer(this.rapidConfig, this.nettyProcessor);

        //4.创建http客户端
        nettyHttpClient = new NettyHttpClient(rapidConfig, nettyHttpServer.getEventLoopGroupWork());
    }

    @Override
    public void start() {
        this.nettyProcessor.start();
        this.nettyHttpServer.start();
        this.nettyHttpClient.start();
        log.info("rapidContainer start");
    }

    @Override
    public void shutdown() {
        this.nettyProcessor.shutdown();
        this.nettyHttpServer.shutdown();
        this.nettyHttpClient.shutdown();
    }
}
